layui.use(['table', 'admin', 'ax', 'func','laydate', 'form', 'layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var form = layui.form;
    var layer = layui.layer;

    /**
     * 东更道-钉钉-月度-考勤查询管理
     */
    var DgdDingdingMonthAttend = {
        tableId: "dgdDingdingMonthAttendTable"
    };

    //默认上个月
    var lastmonth = new Date().getMonth() == '0' ? new Date().getFullYear() - 1 + "-" + 12 : (new Date().getMonth() < 10 ? new Date().getFullYear() + "-0" + new Date().getMonth() : new Date().getFullYear() + "-" + new Date().getMonth());
    //渲染时间选择框
    var lastmonthLaydate = laydate.render({
        elem: '#date',
        format:'yyyy-MM',
        value:lastmonth,//默认上个月
        type: 'month',
        change: function(value){
            lastmonth = value;
        },
        done:function(value,date,startDate){

            $('#firLevel').empty();
            $('#secLevel').val('');
            $('#secLevel').empty();
            $('#thirdLevel').val('');
            $('#thirdLevel').empty();
            $('#fourLevel').val('');
            $('#fourLevel').empty();
            form.render();

            var languageAjax = new $ax(Feng.ctxPath + "/btyDingdingDayDept/qyList");
            languageAjax.set("attendYearMonth", value)
            languageAjax.set("pid", 1)
            var languageResult = languageAjax.start();
            $.each(languageResult.data, function (index, val) {
                $("#firLevel").append("<option value='" + val.did + "'>" + val.name + "</option>");
            });

            $('#firLevel').val('');
            form.render('select');

        }
    });
    // $(function () {
    //     alert(JSON.stringify(lastmonth))
    // })

    /**
     * 检索区域
     */
    //一级区域
    var languageAjax = new $ax(Feng.ctxPath + "/btyDingdingDayDept/qyList");
    // var val = new Date().getMonth() == '0' ? new Date().getFullYear() - 1 + "-" + 12 : (new Date().getMonth() < 10 ? new Date().getFullYear() + "-0" + new Date().getMonth() : new Date().getFullYear() + "-" + new Date().getMonth())
    // languageAjax.set("attendYearMonth", val)
    languageAjax.set("attendYearMonth", lastmonth)
    languageAjax.set("pid", 1)
    var languageResult = languageAjax.start();
    $.each(languageResult.data, function (index, val) {
        $("#firLevel").append("<option value='" + val.did + "'>" + val.name + "</option>");
    });
    form.render('select');

    //二级区域
   form.on('select(firLevel)', function (data) {
        var firId = data.value;
        if (firId == "") {
            $("#secLevel").html("");
            $("#secLevel").append("<option value=''>全部</option>");
            form.render('select');
        } else {
            var qyAjax = new $ax("/btyDingdingDayDept/qyList");
            qyAjax.set("pid", firId);
            // qyAjax.set("attendYearMonth", val)
            qyAjax.set("attendYearMonth", lastmonth)
            var qyResult = qyAjax.start();
            $("#secLevel").html("");
            $("#secLevel").append("<option value=''>全部</option>");
            $.each(qyResult.data, function (index, data) {
                $("#secLevel").append("<option value='" + data.did + "'>" + data.name + "</option>");
            });
            form.render('select');
        }
    });

        //二级区域
    // var languageAjax = new $ax(Feng.ctxPath + "/dgdDingdingDayDept/qyList");
    // languageAjax.set("attendYearMonth", lastmonth)
    // languageAjax.set("pid", 529205900)
    // var languageResult = languageAjax.start();
    // $.each(languageResult.data, function (index, val) {
    //     $("#secLevel").append("<option value='" + val.did + "'>" + val.name + "</option>");
    // });
    // form.render('select');


    //三级区域
    form.on('select(secLevel)', function (data) {
        var secId = data.value;
        if (secId == "") {
            $("#thirdLevel").html("");
            $("#thirdLevel").append("<option value=''>全部</option>");
            form.render('select');
        } else {
            var qyAjax = new $ax("/btyDingdingDayDept/qyList");
            qyAjax.set("pid", secId);
            // qyAjax.set("attendYearMonth", val)
            qyAjax.set("attendYearMonth", lastmonth)
            var qyResult = qyAjax.start();
            $("#thirdLevel").html("");
            $("#thirdLevel").append("<option value=''>全部</option>");
            $.each(qyResult.data, function (index, data) {
                $("#thirdLevel").append("<option value='" + data.did + "'>" + data.name + "</option>");
            });
            form.render('select');
        }
    });

    //四级区域
    form.on('select(thirdLevel)', function (data) {
        var third = data.value;
        if (third == "") {
            $("#fourLevel").html("");
            $("#fourLevel").append("<option value=''>全部</option>");
            form.render('select');
        } else {
            var qyAjax = new $ax("/btyDingdingDayDept/qyList");
            qyAjax.set("pid", third);
            // qyAjax.set("attendYearMonth", val)
            qyAjax.set("attendYearMonth", lastmonth)
            var qyResult = qyAjax.start();
            $("#fourLevel").html("");
            $("#fourLevel").append("<option value=''>全部</option>");
            $.each(qyResult.data, function (index, data) {
                $("#fourLevel").append("<option value='" + data.did + "'>" + data.name + "</option>");
            });
            form.render('select');
        }
    });

    /**
     * 初始化表格的列
     */
    DgdDingdingMonthAttend.initColumn = function () {
        return [[
            // {type: 'checkbox'},
            {type: 'numbers',align:'center', title: '序号'},
            {field: 'attendYearMonth', title: '月份',width:80},
            {field: 'id', hide: true, title: '主键;主键id'},
            {field: 'deptName', title: '部门'},
            {field: 'empName', title: '姓名'},
            {field: 'empId', title: '员工ID'},
            {field: 'attendDayNum', title: '出勤',width:60},
            // {field: 'attendWorkHours', title: '工作时长'},
            {field: 'attendWorkMinutes', title: '工作时长',width:90},
            {field: 'lackAttendNum', title: '缺卡次数',width:90},
            {field: 'lackAttendFine', title: '缺卡扣款',width:90},
            {field: 'lateNum', sort: true, title: '迟到次数',width:110},
            {field: 'lateMinutes', sort: true, title: '迟到分钟数',width:120},
            {field: 'lateFine', title: '迟到扣款',width:90},
            // {field: 'leaveEarlyNum', sort: true, title: '早退次数'},
            // {field: 'leaveEarlyMinutes', sort: true, title: '早退分钟数'},
            // {field: 'requestNum', sort: true, title: '关联表单数量'},
            // {field: 'requestOutNum', sort: true, title: '关联外出表单次数'},
            {field: 'requestOutHours', title: '外出申请', templet: function (d) {
                    if (d.requestOutHours === '') {
                        return "0";
                    } else {
                        return d.requestOutHours;
                    }
                }},
            {field: 'askLeaveDay', title: '请假', width:60,templet: function (d) {
                    if (d.askLeaveDay === '') {
                        return "0";
                    } else {
                        return d.askLeaveDay;
                    }
                }},
            // {field: 'requestOutMinutes', sort: true, title: '外出表单时间分钟数'},
            // {field: 'createTime', sort: true, title: '创建时间;创建时间'},
            // {field: 'createUser', sort: true, title: '创建人;创建人id'},
            // {field: 'updateTime', sort: true, title: '更新时间;更新时间'},
            // {field: 'updateUser', sort: true, title: '更新人;更新人id'},
            {field: 'attendUpdateNoteNum', sort: true, title: '备注'},
            {align: 'center', toolbar: '#tableBar', title: '操作',width: 250}
        ]];
    };

    /**
     * 点击查询按钮
     */
    DgdDingdingMonthAttend.search = function () {
        var queryData = {};

        queryData['firLevel'] = $("#firLevel").val();
        queryData['secLevel'] = $("#secLevel").val();
        queryData['thirdLevel'] = $("#thirdLevel").val();
        queryData['fourLevel'] = $("#fourLevel").val();
        queryData['attendYearMonth'] = $("#date").val();
        queryData['empName'] = $("#empName").val();
        queryData['empId'] = $("#empId").val();

        table.reload(DgdDingdingMonthAttend.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 跳转到添加页面
     */
    DgdDingdingMonthAttend.jumpAddPage = function () {
        window.location.href = Feng.ctxPath + '/btyDingdingMonthAttend/add'
    };

    /**
    * 跳转到编辑页面
    *
    * @param data 点击按钮时候的行数据
    */
    DgdDingdingMonthAttend.jumpEditPage = function (data) {
        window.location.href = Feng.ctxPath + '/btyDingdingMonthAttend/edit?id=' + data.id
    };

    /**
     * 导出excel按钮
     */
    DgdDingdingMonthAttend.exportExcel = function () {
        var date = $('#date').val();
        var ajax = new $ax("/btyDingdingMonthAttend/export", function (data) {
        }, function (data) {
        });
        ajax.set("attendYearMonth", date);
        ajax.set("firLevel", $("#firLevel").val());
        ajax.set("secLevel", $("#secLevel").val());
        ajax.set("thirdLevel", $("#thirdLevel").val());
        ajax.set("fourLevel", $("#fourLevel").val());
        ajax.set("empName", $("#empName").val());
        ajax.set("empId", $("#empId").val());


        const result = ajax.start();

        for (index in result) {
            var empId = result[index].empId;
            result[index].empId = empId + "\t";
        }
        table.exportFile(tableResult.config.id, result, 'xls');
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    DgdDingdingMonthAttend.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/btyDingdingMonthAttend/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(DgdDingdingMonthAttend.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + DgdDingdingMonthAttend.tableId,
        url: Feng.ctxPath + '/btyDingdingMonthAttend/list',
        page: true,
        limit:20,
        height: "full-118",
        cellMinWidth: 100,
        cols: DgdDingdingMonthAttend.initColumn(),
        where: {attendYearMonth: lastmonth},
        done:function (res,index) {
            var that = this.elem.next();

            res.data.forEach(function (item, index) {
                var td = that.find(".layui-table-box tbody tr[data-index='" + index + "'] td[data-field='lackAttendNum']");
                var td1 = that.find(".layui-table-box tbody tr[data-index='" + index + "'] td[data-field='askLeaveDay']");
                var td2 = that.find(".layui-table-box tbody tr[data-index='" + index + "'] td[data-field='attendUpdateNoteNum']");
                var td3 = that.find(".layui-table-box tbody tr[data-index='" + index + "'] td[data-field='lateNum']");


                if (item.lackAttendNum > 2){
                    td.css("background-color", "red");
                    td.css("color", "white");
                }
                if (item.askLeaveDay > 0){
                    td1.css("background-color", "red");
                    td1.css("color", "white");
                }
                if (item.attendUpdateNoteNum > 0){
                    td2.css("background-color", "red");
                    td2.css("color", "white");
                }

                if (item.lateNum > 0){
                    td3.css("background-color", "red");
                    td3.css("color", "white");
                }
            })
            }
    });

    // 重置按钮事件
    $('#btnReset').click(function () {

        $('#firLevel').val('');
        $('#secLevel').val('');
        $('#thirdLevel').val('');
        $('#fourLevel').val('');
        $("#empName").val('');
        $("#empId").val('');
        //默认上个月
        var lastmonth = new Date().getMonth() == '0' ? new Date().getFullYear() - 1 + "-" + 12 : (new Date().getMonth() < 10 ? new Date().getFullYear() + "-0" + new Date().getMonth() : new Date().getFullYear() + "-" + new Date().getMonth());

        $("#date").val(lastmonth);
        form.render();
    });


    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        DgdDingdingMonthAttend.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

    DgdDingdingMonthAttend.jumpAddPage();

    });

    /**
     * 异常详情
     */
    DgdDingdingMonthAttend.onDetailItem = function (data) {

        layer.open({
            type: 2,
            title: '考勤详情',
            area: ['800px', '500px'],
            content: Feng.ctxPath + "/btyDingdingMonthAttend/detail_view/" + data.empId + "/" + data.attendYearMonth,
        });


        // func.open({
        //     height: 500,
        //     width: '500px',
        //     title: '考勤详情',
        //     content: Feng.ctxPath + "/dgdDingdingMonthAttend/detail_view/" + data.empId + "/" + data.attendYearMonth,
        //     tableId: DgdDingdingMonthAttend.tableId
        // });
    };

    /**
     * 月度详情
     */
    DgdDingdingMonthAttend.onMonDetailItem = function (data) {

        var index = layer.open({
            type: 2,
            title: '月度详情',
            area: ['900px', '600px'],
            content: Feng.ctxPath + "/btyDingdingDayAttend/monDetail_view/" + data.empId + "/" + data.attendYearMonth,
        });
        layer.full(index)
    };

    // 导出excel
    $('#btnExp').click(function () {
        DgdDingdingMonthAttend.exportExcel();
    });

    // 同步
    $('#sync').click(function () {
        DgdDingdingMonthAttend.sync();
    });

    /**
     * 同步
     */
    DgdDingdingMonthAttend.sync = function () {
         layer.open({
            type: 1,
            title: '同步',
            area: ['200px', '200px'],
            btn: ["确定", "取消"],
             async: false,
             content: "<div class=\"layui-inline\">\n" +
                "<label class=\"layui-form-label layui-inline shop-name\">月份</label>\n" +
                "<div class=\"layui-inline\" style=\"display: inline-block\">\n" +
                "<input id=\"attendYearMonth\" class=\"layui-input\" type=\"text\" placeholder=\"请输入月份\" style=\"width: 110px\" autocomplete=\"off\"/>\n" +
                "</div>\n" +
                "</div>",
            yes: function (index) {
                layer.close(index);
                var object = {};
                object.attendYearMonth = $("#attendYearMonth").val();
                setTimeout(()=>{
                    $.ajax({
                        type: "POST",
                        url: "/btyDingdingMonthAttend/taskSynchronousAttend",
                        data: JSON.stringify(object),
                        async: false,
                        contentType: 'application/json',
                        success: function (data) {
                            if (data.code != 200) {
                                Feng.error(data.message);
                            }else {
                                Feng.success("同步成功！");
                            }
                        },
                        error: function (data) {
                            layer.alert('同步失败！');
                        }
                    });
                },1000)
            }
        });
    };

    // 工具条点击事件
    table.on('tool(' + DgdDingdingMonthAttend.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            DgdDingdingMonthAttend.jumpEditPage(data);
        } else if (layEvent === 'delete') {
            DgdDingdingMonthAttend.onDeleteItem(data);
        } else if (layEvent === 'detail') {
            DgdDingdingMonthAttend.onDetailItem(data);
        } else if (layEvent === 'monDetail') {
            DgdDingdingMonthAttend.onMonDetailItem(data);
        }
    });
});
